#include <iostream>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>  
#include <sys/types.h>  
#include <netinet/in.h>  
#include <arpa/inet.h>
#include <string>
#include <string.h>
#include "ctl_car_msg.h"
using namespace std;

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 9995
#define BUFSIZE 1024

//g++ -lpthread -o client client.c 
int getSocket(){
    int fd =socket( AF_INET, SOCK_STREAM, 0 );
    cout<<"fd="<<fd<<endl;
    if(-1 == fd){
        cout<<"Error, fd is -1"<<endl;
    }
    return fd;
}

/**
 * 连接到server端，如果成功，返回fd，如果失败返回-1
 */
int connectServer(){
    int fd = getSocket();
    cout<<"fd= "<<fd<<endl;
    if(-1 == fd){
        cout<<"Error, connectServer() quit"<<endl;
        return -1;
    }
    struct sockaddr_in remote_addr; //服务器端网络地址结构体
    memset(&remote_addr,0,sizeof(remote_addr)); //数据初始化--清零
    remote_addr.sin_family=AF_INET; //设置为IP通信
    remote_addr.sin_addr.s_addr=inet_addr(SERVER_IP);//服务器IP地址
    remote_addr.sin_port=htons(SERVER_PORT); //服务器端口号
    int con_result = connect(fd, (struct sockaddr*) &remote_addr, sizeof(struct sockaddr));
    if(con_result < 0){
        cout<<"Connect Error!"<<endl;
        return -1;
    }
    cout<<"con_result="<<con_result<<endl;
    return fd;
}

/**
*** 连接到server端，并且不断往server端发送心跳数据
*/
void* heartBeat(void* arg){
    ctl_car_msg ctlmsg;
    char* buf;
    int len,ret;
    ctlmsg.user_id = 1;
    ctlmsg.cmd = CTL_CAR_CMD_MOVE_ON;
    ctlmsg.device_number = DEVICE_ALL_WHEELS;
    int ret = serialize_ctlcar_msg(&ctlmsg,&msg,&len);

    cout<<"Heart bead started!"<<endl;
    int fd = connectServer();
    if(fd<0){
        cout<<"Heart bead quit!"<<endl;
        return 0;
    }
    //char buf[BUFSIZE];  //数据传送的缓冲区
    char buf_read[BUFSIZE];
    //string value = "This is heart beat msg!";
    //strcpy(buf, value.c_str());    
    while(true){
        cout<<"to write data"<<endl;
        printf("%.*s",buf,len);
        int write_num = write(fd, buf, len);
        cout<<"write_num="<<write_num<<endl;
        int read_num = read(fd,buf_read,BUFSIZE);
        if(read_num>0){
                cout<<"read data:"<<buf_read<<endl;
                memset(buf_read,0,read_num);
        }       
        sleep(2);
    }
    cout<<"Heart bead finished!"<<endl;
    return 0;
}


/**
*** 创建一个新线程，在新线程里调用heartBeat()函数
*/
void threadCall(){
    pthread_t thread;
    pthread_create(&thread,NULL,heartBeat,NULL);
    pthread_detach(thread);
}
int main() {
    cout << "main started" << endl; // prints Hello World!!!
    threadCall();
sleep(10000000);
    cout<<"main finished"<<endl;
    return 0;
}
